<template>
  <el-dialog 
    :title="dialogTitle" 
    v-model="visible"
    width="60%"
    @closed="handleClosed"
  >
    <el-form 
      ref="formRef"
      :model="formData" 
      label-width="120px"
      :rules="rules"
    >
      <!-- 基础信息 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="formData.username" :disabled="!!formData.id" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="姓名" prop="name">
            <el-input v-model="formData.name" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="手机号" prop="phone">
            <el-input v-model="formData.phone" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="性别" prop="gender">
            <el-radio-group v-model="formData.gender">
              <el-radio :label="1">男</el-radio>
              <el-radio :label="2">女</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="入职日期" prop="entryDate">
            <el-date-picker 
              v-model="formData.entryDate" 
              type="date" 
              style="width: 100%" 
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="薪资" prop="salary">
            <el-input-number v-model.number="formData.salary" style="width: 100%" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="所属部门" prop="deptName">
            <el-select v-model="formData.deptName" placeholder="请选择部门" style="width: 100%">
              <el-option
                v-for="dept in departments"
                :key="dept.id"
                :label="dept.name"
                :value="dept.name"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="职位" prop="job">
            <el-select v-model="formData.job" placeholder="请选择职位" style="width: 100%">
              <el-option
                v-for="(label, value) in positionMap"
                :key="value"
                :label="label"
                :value="parseInt(value)"
              />
            </el-select>
          </el-form-item>
        </el-col>
        
        <!-- 工作经验 -->
        <el-col :span="24">
          <el-form-item label="工作经验">
            <el-table :data="formData.exprList" border style="width: 100%">
              <el-table-column prop="company" label="公司名称" width="150">
                <template #default="{ row }">
                  <el-input v-model="row.company" />
                </template>
              </el-table-column>
              <el-table-column prop="job" label="职位" width="120">
                <template #default="{ row }">
                  <el-input v-model="row.job" />
                </template>
              </el-table-column>
              <el-table-column prop="begin" label="开始日期">
                <template #default="{ row }">
                  <el-date-picker v-model="row.begin" type="date" style="width: 100%" value-format="YYYY-MM-DD"/>
                </template>
              </el-table-column>
              <el-table-column prop="end" label="结束日期">
                <template #default="{ row }">
                  <el-date-picker v-model="row.end" type="date" style="width: 100%" value-format="YYYY-MM-DD"/>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="80">
                <template #default="{ $index }">
                  <el-button 
                    type="danger" 
                    size="small"
                    @click="removeExperience($index)"
                  >删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-button 
              type="primary" 
              size="small"
              @click="addExperience"
              style="margin-top: 10px;"
            >添加经历</el-button>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 操作按钮 -->
      <el-form-item>
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">保存</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script setup>
import { 
  ref, 
  defineProps, 
  defineEmits, 
  onMounted, 
  watch,
  computed 
} from 'vue'
import { 
  addEmployee, 
  updateEmployee, 
  getDepartment,
  getEmployeeById
} from '../../services/auth'
import { ElMessage } from 'element-plus'

// 定义props
const props = defineProps({
  modelValue: {
    type: Boolean,
    required: true
  },
  employeeId: {  // 新增的prop，用于接收员工ID
    type: [Number, String],
    default: null
  }
})

// 定义事件
const emit = defineEmits(['update:modelValue', 'success'])

// 部门数据
const departments = ref([])
const fetchDepartments = async () => {
  try {
    const response = await getDepartment()
    if (response.data.code === 1) {
      departments.value = response.data.data
    }
  } catch (error) {
    console.error('获取部门失败:', error)
  }
}

// 根据部门名称获取对应的部门ID
const deptId = computed(() => {
  const dept = departments.value.find(d => d.name === formData.value.deptName)
  return dept ? dept.id : null
})
// 职位映射
const positionMap = {
  1: '班主任',
  2: '讲师',
  3: '学工主管',
  4: '教研主管',
  5: '咨询师'
}

// 表单数据
const formData = ref({
  id: null,
  username: '',
  name: '',
  gender: 1,
  phone: '',
  entryDate: '',
  deptId: null,
  job: null,
  salary: 0,
  exprList: [],
  deptName:''
})

// 重置表单
const resetForm = () => {
  formData.value = {
    id: null,
    username: '',
    name: '',
    gender: 1,
    phone: '',
    entryDate: '',
    deptId: null,
    job: null,
    salary: 0,
    exprList: [],
    deptName:''
  }
}

// 对话框可见性
const visible = ref(false)
const dialogTitle = ref('添加员工')

// 监听modelValue变化
watch(() => props.modelValue, (newVal) => {
  visible.value = newVal
  if (newVal) {
    resetForm()
    
    // 如果有employeeId，则加载该员工信息
    if (props.employeeId) {
      loadEmployeeData(props.employeeId)
      dialogTitle.value = '编辑员工信息'
    } else {
      dialogTitle.value = '添加新员工'
    }
  }
})

// 加载员工数据
const loadEmployeeData = async (id) => {
  try {
    // 确保部门数据已加载
    if (!departments.value || departments.value.length === 0) {
      await fetchDepartments()
    }

    // 再次检查 departments.value 是否已加载
    if (!departments.value || departments.value.length === 0) {
      console.error('部门数据加载失败')
      return
    }

    // 获取员工信息
    const response = await getEmployeeById(id)
    if (response.data.code === 1) {
      const employeeData = response.data.data

      // 将员工数据填充到表单中
      formData.value = {
        id: employeeData.id,
        username: employeeData.username || '',
        name: employeeData.name || '',
        gender: employeeData.gender || 1,
        phone: employeeData.phone || '',
        entryDate: employeeData.entryDate || '',
        deptName: '', // 初始化为空
        job: employeeData.job || null,
        salary: employeeData.salary || 0,
        exprList: employeeData.exprList || []
      }

      // 回显部门名称
      if (employeeData.deptId !== null && employeeData.deptId !== undefined) {
        const dept = departments.value.find(d => d.id === employeeData.deptId)
        if (dept) {
          formData.value.deptName = dept.name
        } else {
          // 如果查找不到部门，默认为空
          formData.value.deptName = ''
        }
      }
    } else {
      ElMessage.error('获取员工信息失败')
    }
  } catch (error) {
    console.error('获取员工信息异常:', error)
    ElMessage.error('网络请求失败')
  }
}

// 提交表单
const submitForm = async () => {
  try {
    // 构造提交数据，注入 deptId
    const submitData = {
      ...formData.value,
      deptId: deptId.value
    }

    delete submitData.deptName // 不需要提交 deptName

    const response = formData.value.id 
      ? await updateEmployee(submitData) 
      : await addEmployee(submitData)

    if (response.data.code === 1) {
      ElMessage.success(`${dialogTitle.value}成功`)
      visible.value = false
      emit('success')
    } else {
      ElMessage.error(`${dialogTitle.value}失败`)
    }
  } catch (error) {
    console.error(`${dialogTitle.value}异常:`, error)
    ElMessage.error('网络请求失败')
  }
}

// 添加工作经历
const addExperience = () => {
  formData.value.exprList.push({
    company: '',
    job: '',
    begin: '',
    end: ''
  })
}

// 删除工作经历
const removeExperience = (index) => {
  formData.value.exprList.splice(index, 1)
}

// 对话框关闭回调
const handleClosed = () => {
  emit('update:modelValue', false)
}

// 页面加载时获取部门数据
onMounted(() => {
  fetchDepartments()
})
</script>

<style scoped>
.el-table {
  margin-bottom: 10px;
}
</style>